const { exec } = require("child_process")
const fs = require("fs-extra")
const path = require("path")

const cmd = `javascript-obfuscator --config ./config/javascript-obfuscator/obfuscator.conf.js src/views/CIF`

const fromDir = (startPath, filter, callback) => {
  console.log("Starting from dir " + startPath + "/")

  if (!fs.existsSync(startPath)) {
    console.log("no dir ", startPath)
    return
  }

  const files = fs.readdirSync(startPath)
  for (let i = 0; i < files.length; i++) {
    const filename = path.join(startPath, files[i])
    const stat = fs.lstatSync(filename)
    if (stat.isDirectory()) {
      fromDir(filename, filter, callback) //recurse
    } else if (filename.indexOf(filter) >= 0) {
      console.log("-- found: ", filename)
      callback(filename)
      // const replacedName = filename.replace(filter, "")
      // fs.rmSync(replacedName)
      // fs.renameSync(filename, replacedName)
    }
  }
}

// fs.removeSync(path.resolve(__dirname, '../../dist'))
// fs.ensureDirSync(path.resolve(__dirname, '../../dist/CIF'))

exec(cmd, function (error, stdout, stderr) {
  if (process.env.NODE_ENV !== "production") {
    console.log("CIF.CP.buildPkg:exec stdout ", stdout)
  }

  if (error !== null) {
    if (process.env.NODE_ENV !== "production") {
      console.log("CIF.CP.buildPkg:exec error ", error)
    }
  }
  fromDir(path.resolve(__dirname, "../../src/views/CIF") , "-obfuscated", function (filename) {
    const replacedName = filename.replace("-obfuscated", "")
    fs.rmSync(replacedName)
    fs.renameSync(filename, replacedName)
  })
  // fs.copy(path.resolve(__dirname, "../../src/views/CIF") , path.resolve(__dirname, "../../dist/CIF"),() => {
  //   fromDir(path.resolve(__dirname, "../../src/CIF") , "-obfuscated", function (filename) {
  //     fs.rmSync(filename)
  //   })
  //   fromDir(path.resolve(__dirname, "../../dist/CIF") , "-obfuscated", function (filename) {
  //     const replacedName = filename.replace("-obfuscated", "")
  //     fs.rmSync(replacedName)
  //     fs.renameSync(filename, replacedName)
  //   })
  //   fs.removeSync(path.resolve(__dirname, '../../src/views/CIF'));
  //   fs.copy(path.resolve(__dirname, "../../dist/CIF"), path.resolve(__dirname, "../../src/views/CIF"), ()=>{
  //     fs.removeSync(path.resolve(__dirname, '../../dist'));
  //   })
  // })
})